<template>
  <div class="my-exams">
    <!-- 统计概览 -->
    <div class="stats-overview">
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><Document /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.totalExams }}</div>
            <div class="stat-label">参加考试</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon passed">
            <el-icon><CircleCheck /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.passedExams }}</div>
            <div class="stat-label">通过考试</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.averageScore }}</div>
            <div class="stat-label">平均分数</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><Medal /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.certificates }}</div>
            <div class="stat-label">获得证书</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <div class="filter-left">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索考试名称..."
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <div class="filter-right">
        <el-select v-model="statusFilter" placeholder="考试状态" @change="handleFilter">
          <el-option label="全部状态" value="" />
          <el-option label="已通过" value="passed" />
          <el-option label="未通过" value="failed" />
          <el-option label="进行中" value="ongoing" />
        </el-select>
        
        <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort">
          <el-option label="最近考试" value="recent" />
          <el-option label="分数高低" value="score" />
          <el-option label="考试名称" value="name" />
        </el-select>
      </div>
    </div>

    <!-- 考试记录列表 -->
    <div class="exams-list">
      <div class="list-header">
        <h3>考试记录</h3>
        <span class="record-count">共 {{ filteredExams.length }} 条记录</span>
      </div>
      
      <div class="exams-table">
        <el-table 
          :data="paginatedExams" 
          style="width: 100%"
          @row-click="viewExamDetail"
        >
          <el-table-column prop="examTitle" label="考试名称" min-width="200">
            <template #default="{ row }">
              <div class="exam-title-cell">
                <div class="exam-name">{{ row.examTitle }}</div>
                <div class="exam-category">{{ row.category }}</div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="score" label="分数" width="100" align="center">
            <template #default="{ row }">
              <div class="score-cell" :class="getScoreClass(row.score)">
                {{ row.score }}分
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="completedAt" label="考试时间" width="150" align="center">
            <template #default="{ row }">
              {{ formatDate(row.completedAt) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="duration" label="用时" width="100" align="center" />
          
          <el-table-column prop="ranking" label="排名" width="100" align="center" />
          
          <el-table-column label="操作" width="200" align="center">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button size="small" @click.stop="viewResult(row)">
                  查看详情
                </el-button>
                <el-button 
                  size="small" 
                  type="primary" 
                  @click.stop="retakeExam(row)"
                  v-if="row.status !== 'ongoing'"
                >
                  重新考试
                </el-button>
                <el-button 
                  size="small" 
                  @click.stop="downloadCertificate(row)"
                  v-if="row.status === 'passed'"
                >
                  下载证书
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="filteredExams.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredExams.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      
      <!-- 空状态 -->
      <div v-if="filteredExams.length === 0" class="empty-state">
        <EmptyState
          image="/images/empty-exams.svg"
          title="暂无考试记录"
          description="您还没有参加过任何考试"
        >
          <el-button type="primary" @click="goToExamList">
            去参加考试
          </el-button>
        </EmptyState>
      </div>
    </div>

    <!-- 成绩趋势图 -->
    <div class="score-trend" v-if="examRecords.length > 0">
      <div class="trend-header">
        <h3>成绩趋势</h3>
        <div class="trend-controls">
          <el-radio-group v-model="trendPeriod" size="small">
            <el-radio-button label="week">最近一周</el-radio-button>
            <el-radio-button label="month">最近一月</el-radio-button>
            <el-radio-button label="quarter">最近三月</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      
      <div class="trend-chart">
        <div class="chart-placeholder">
          <el-icon><TrendCharts /></el-icon>
          <span>成绩趋势图</span>
          <p>显示您在不同时间段的考试成绩变化</p>
        </div>
      </div>
    </div>

    <!-- 学习建议 -->
    <div class="learning-suggestions" v-if="suggestions.length > 0">
      <h3>学习建议</h3>
      <div class="suggestions-grid">
        <div 
          v-for="suggestion in suggestions" 
          :key="suggestion.id"
          class="suggestion-card"
        >
          <div class="suggestion-icon">
            <el-icon><Lightbulb /></el-icon>
          </div>
          <div class="suggestion-content">
            <div class="suggestion-title">{{ suggestion.title }}</div>
            <div class="suggestion-desc">{{ suggestion.description }}</div>
          </div>
          <div class="suggestion-action">
            <el-button size="small" @click="applySuggestion(suggestion)">
              查看详情
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Document, CircleCheck, TrendCharts, Medal, Search, Lightbulb
} from '@element-plus/icons-vue'
import EmptyState from '@/components/global/EmptyState.vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const statusFilter = ref('')
const sortBy = ref('recent')
const currentPage = ref(1)
const pageSize = ref(10)
const trendPeriod = ref('month')

// 统计数据
const stats = ref({
  totalExams: 15,
  passedExams: 12,
  averageScore: 85,
  certificates: 8
})

// 考试记录数据
const examRecords = ref([
  {
    id: 1,
    examId: 1,
    examTitle: 'JavaScript基础能力测试',
    category: '前端开发',
    score: 92,
    status: 'passed',
    completedAt: new Date('2024-01-15'),
    duration: '25分钟',
    ranking: '前10%'
  },
  {
    id: 2,
    examId: 2,
    examTitle: 'Vue.js框架认证考试',
    category: '前端框架',
    score: 88,
    status: 'passed',
    completedAt: new Date('2024-01-10'),
    duration: '35分钟',
    ranking: '前15%'
  },
  {
    id: 3,
    examId: 3,
    examTitle: 'CSS样式设计测试',
    category: '前端开发',
    score: 76,
    status: 'passed',
    completedAt: new Date('2024-01-05'),
    duration: '20分钟',
    ranking: '前30%'
  },
  {
    id: 4,
    examId: 4,
    examTitle: 'HTML结构基础测试',
    category: '前端开发',
    score: 58,
    status: 'failed',
    completedAt: new Date('2024-01-01'),
    duration: '18分钟',
    ranking: '前70%'
  },
  {
    id: 5,
    examId: 5,
    examTitle: 'React高级开发认证',
    category: '前端框架',
    score: 0,
    status: 'ongoing',
    completedAt: new Date(),
    duration: '进行中',
    ranking: '-'
  }
])

// 学习建议
const suggestions = ref([
  {
    id: 1,
    title: '加强基础知识',
    description: '建议重点复习HTML和CSS基础知识，提高基础技能掌握度'
  },
  {
    id: 2,
    title: '实践项目练习',
    description: '通过实际项目练习来巩固所学的前端开发技能'
  },
  {
    id: 3,
    title: '关注新技术',
    description: '学习最新的前端技术和框架，保持技术敏感度'
  }
])

// 计算属性
const filteredExams = computed(() => {
  let filtered = examRecords.value

  // 搜索筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(exam => 
      exam.examTitle.toLowerCase().includes(keyword) ||
      exam.category.toLowerCase().includes(keyword)
    )
  }

  // 状态筛选
  if (statusFilter.value) {
    filtered = filtered.filter(exam => exam.status === statusFilter.value)
  }

  // 排序
  switch (sortBy.value) {
    case 'score':
      filtered.sort((a, b) => b.score - a.score)
      break
    case 'name':
      filtered.sort((a, b) => a.examTitle.localeCompare(b.examTitle))
      break
    default: // recent
      filtered.sort((a, b) => new Date(b.completedAt) - new Date(a.completedAt))
  }

  return filtered
})

const paginatedExams = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredExams.value.slice(start, end)
})

// 方法
const getScoreClass = (score) => {
  if (score >= 90) return 'excellent'
  if (score >= 80) return 'good'
  if (score >= 60) return 'pass'
  return 'fail'
}

const getStatusType = (status) => {
  const types = {
    'passed': 'success',
    'failed': 'danger',
    'ongoing': 'warning'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    'passed': '已通过',
    'failed': '未通过',
    'ongoing': '进行中'
  }
  return texts[status] || '未知'
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleFilter = () => {
  currentPage.value = 1
}

const handleSort = () => {
  currentPage.value = 1
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const viewExamDetail = (row) => {
  router.push(`/exam/detail/${row.examId}`)
}

const viewResult = (row) => {
  router.push(`/exam/result/${row.id}`)
}

const retakeExam = (row) => {
  router.push(`/exam/detail/${row.examId}`)
}

const downloadCertificate = (row) => {
  ElMessage.success('正在下载证书...')
}

const goToExamList = () => {
  router.push('/exam/list')
}

const applySuggestion = (suggestion) => {
  ElMessage.info(`查看建议：${suggestion.title}`)
}

onMounted(() => {
  // 初始化数据
})
</script>

<style lang="scss" scoped>
.my-exams {
  min-height: 100vh;
  background: var(--el-bg-color-page);
  padding: 20px;
}

.stats-overview {
  margin-bottom: 24px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.stat-card {
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  display: flex;
  align-items: center;
  gap: 16px;
  
  .stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--el-color-primary-light-9);
    color: var(--el-color-primary);
    font-size: 24px;
    
    &.passed {
      background: var(--el-color-success-light-9);
      color: var(--el-color-success);
    }
  }
  
  .stat-content {
    .stat-number {
      font-size: 24px;
      font-weight: 700;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }
    
    .stat-label {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }
}

.filter-section {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 24px;
  
  @media (max-width: 768px) {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
}

.filter-left {
  .el-input {
    width: 300px;
    
    @media (max-width: 768px) {
      width: 100%;
    }
  }
}

.filter-right {
  display: flex;
  gap: 12px;
  
  @media (max-width: 768px) {
    justify-content: space-between;
  }
  
  .el-select {
    width: 120px;
  }
}

.exams-list {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  margin-bottom: 24px;
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 24px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  h3 {
    font-size: 18px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
  
  .record-count {
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }
}

.exam-title-cell {
  .exam-name {
    font-weight: 500;
    margin-bottom: 4px;
    color: var(--el-text-color-primary);
  }
  
  .exam-category {
    font-size: 12px;
    color: var(--el-text-color-placeholder);
  }
}

.score-cell {
  font-weight: 600;
  
  &.excellent {
    color: var(--el-color-success);
  }
  
  &.good {
    color: var(--el-color-primary);
  }
  
  &.pass {
    color: var(--el-color-warning);
  }
  
  &.fail {
    color: var(--el-color-danger);
  }
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  flex-wrap: wrap;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.score-trend {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  margin-bottom: 24px;
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 24px;
}

.trend-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  h3 {
    font-size: 18px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.trend-chart {
  height: 300px;
  background: var(--el-fill-color-extra-light);
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  
  .chart-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    color: var(--el-text-color-placeholder);
    text-align: center;
    
    .el-icon {
      font-size: 48px;
    }
    
    span {
      font-size: 16px;
      font-weight: 500;
    }
    
    p {
      font-size: 14px;
      margin: 0;
    }
  }
}

.learning-suggestions {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  max-width: 1200px;
  margin: 0 auto;
  
  h3 {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 20px;
    color: var(--el-text-color-primary);
  }
}

.suggestions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.suggestion-card {
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  padding: 20px;
  display: flex;
  gap: 16px;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: var(--el-color-primary);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
  
  .suggestion-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: var(--el-color-warning-light-9);
    color: var(--el-color-warning);
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
  }
  
  .suggestion-content {
    flex: 1;
    
    .suggestion-title {
      font-weight: 500;
      margin-bottom: 8px;
      color: var(--el-text-color-primary);
    }
    
    .suggestion-desc {
      font-size: 14px;
      color: var(--el-text-color-secondary);
      line-height: 1.5;
    }
  }
  
  .suggestion-action {
    display: flex;
    align-items: center;
  }
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .suggestions-grid {
    grid-template-columns: 1fr;
  }
  
  .suggestion-card {
    flex-direction: column;
    text-align: center;
    
    .suggestion-action {
      justify-content: center;
    }
  }
}
</style>
